﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;

namespace SimpleTiles
{
    public partial class CropImage : PhoneApplicationPage
    {
        private int trX = 0;
        private int trY = 0;
        const int MINSIZE = 173;
        private Rectangle rect;
       // private Boolean isMove = false;

        //private TransformGroup transformGroup;
        //private TranslateTransform translation;
        //private ScaleTransform scale;

        public CropImage()
        {
            
            InitializeComponent();

            image1.Source = App.ChosenPhoto;
            
            SetPicture();

          this.ManipulationDelta +=this.PhoneApplicationPage_ManipulationDelta;
         //this.transformGroup = new TransformGroup();
         // this.translation = new TranslateTransform();
          //this.scale = new ScaleTransform();

          //this.transformGroup.Children.Add(this.scale);
          //this.transformGroup.Children.Add(this.translation);
          //this.rect.RenderTransform = this.transformGroup;
        }

        void SetPicture()
        {
            LayoutRoot.Height = image1.Height;
            LayoutRoot.Width = image1.Width;
    
            this.rect = new Rectangle();
            rect.Opacity = .5;
            rect.Fill = new SolidColorBrush(Colors.White);
            rect.MinHeight = MINSIZE;
            rect.MinWidth = MINSIZE;
            rect.Height = 173;
            rect.Width = 173;
            if (image1.Width > image1.Height)
            {
                rect.MaxHeight = image1.Height;
                rect.MaxWidth = image1.Height;
            }
            else
            {
                rect.MaxHeight = image1.Width;
                rect.MaxWidth = image1.Width;
            }


            rect.Stroke = new SolidColorBrush(Colors.Red);
            rect.StrokeThickness = 2;
            rect.Margin = image1.Margin;
           // rect.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(rect_ManipulationDelta);

            LayoutRoot.Children.Add(rect);
        }
        void PhoneApplicationPage_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            // Scale the rectangle.
            //MessageBox.Show(image1.ActualHeight.ToString());
            double minXYScale = Math.Min(e.DeltaManipulation.Scale.X, e.DeltaManipulation.Scale.Y);
            if (!(rect.Width * minXYScale < MINSIZE) && !(rect.Width * minXYScale > image1.ActualWidth) && !(rect.Height * minXYScale > image1.ActualHeight))
            {
                this.rect.Width *= minXYScale;
                this.rect.Height *= minXYScale;
            }
            else if ((rect.Width * minXYScale > image1.ActualWidth) || (rect.Height * minXYScale > image1.ActualHeight))
            {
                if (image1.ActualWidth > image1.ActualHeight)
                {
                    rect.Height = image1.ActualHeight;
                    rect.Width = image1.ActualHeight;
                }
                else
                {
                    rect.Height = image1.ActualWidth;
                    rect.Width = image1.ActualWidth;
                }
            }
            //else if((rect.Width * minXYScale < MINSIZE))
              //  { rect.Width = MINSIZE; rect.Height = MINSIZE; }

            //MOVE
            GeneralTransform gt = (this.rect).TransformToVisual(LayoutRoot);
            Point p = gt.Transform(new Point(0, 0));
            int intermediateValueY = (int)(LayoutRoot.Height- this.rect.Height);
            int intermediateValueX = (int)(LayoutRoot.Width - this.rect.Width);

            TranslateTransform tr = new TranslateTransform();
            trX += (int)e.DeltaManipulation.Translation.X;
            trY += (int)e.DeltaManipulation.Translation.Y;

            if (trY < (-intermediateValueY / 2))
            {
                trY = (-intermediateValueY / 2);
            }
            else if (trY > (intermediateValueY / 2))
            {
                trY = (intermediateValueY / 2);
            }

            if (trX < (-intermediateValueX / 2))
            {
                trX = (-intermediateValueX / 2);
            }
            else if (trX > (intermediateValueX / 2))
            {
                trX = (intermediateValueX / 2);
            }

            tr.X = trX;
            
            tr.Y = trY;

     
            rect.RenderTransform = tr;
         
   
            
            
         
           
        }

        private void Accept_Click(object sender, EventArgs e)
        {
            ClipImage();

            //WriteBitmap(LayoutRoot);
            //PhoneApplicationService.Current.State["photoClip"] = image1;
            //var image = new BitmapImage();
            //using (var local = new IsolatedStorageFileStream("/Shared/ShellContent/myImage.jpg", FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
           // {
           //     image.SetSource(local);
          //  }

         //   WriteDummyImage(image);
        }
        void ClipImage()
        {
            RectangleGeometry geo = new RectangleGeometry();

            rect = (Rectangle)(from c in LayoutRoot.Children where c.Opacity == .5 select c).First();
            GeneralTransform gt = rect.TransformToVisual(image1);
            Point p = gt.Transform(new Point(0,0));
            geo.Rect = new Rect(p.X, p.Y, rect.Width, rect.Height);
            image1.Clip = geo;
            rect.Visibility = System.Windows.Visibility.Collapsed;

            //TranslateTransform t = new TranslateTransform();
            //t.X = -p.X;
            //t.Y = -p.Y;
            //image1.RenderTransform = t;

            // Get the size of the source image captured by the camera
            WriteableBitmap imageW = new WriteableBitmap(App.ChosenPhoto);
            double originalImageWidth = imageW.PixelWidth;
            double originalImageHeight = imageW.PixelHeight;


            // Get the size of the image when it is displayed on the phone
            double displayedWidth = image1.ActualWidth;
            double displayedHeight = image1.ActualHeight;

            // Calculate the ratio of the original image to the displayed image
            double widthRatio = originalImageWidth / displayedWidth;
            double heightRatio = originalImageHeight / displayedHeight;

            // Create a new WriteableBitmap. The size of the bitmap is the size of the cropping rectangle
            // drawn by the user, multiplied by the image size ratio.
            App.CroppedImage = new WriteableBitmap((int)(widthRatio * rect.Width), (int)(heightRatio *rect.Height));


            // Calculate the offset of the cropped image. This is the distance, in pixels, to the top left corner
            // of the cropping rectangle, multiplied by the image size ratio.
            int xoffset = (int)(p.X * widthRatio);
            int yoffset = (int)(p.Y * heightRatio);

            // Copy the pixels from the targeted region of the source image into the target image, 
            // using the calculated offset
            for (int i = 0; i < App.CroppedImage.Pixels.Length; i++)
            {
                int x = (int)((i % App.CroppedImage.PixelWidth) + xoffset);
                int y = (int)((i / App.CroppedImage.PixelWidth) + yoffset);

                if (!(y * App.ChosenPhoto.PixelWidth + x < 0) && !((y * App.ChosenPhoto.PixelWidth + x) >= App.ChosenPhoto.Pixels.Length))
                    //App.CroppedImage.Pixels[i]=;
                    App.CroppedImage.Pixels[i] = App.ChosenPhoto.Pixels[y * App.ChosenPhoto.PixelWidth + x];
                
                
            }

            // Set the source of the image control to the new cropped bitmap
            //DisplayedImageElement.Source = App.CroppedImage;
            //rect.Visibility = Visibility.Collapsed;

   
            //PhoneApplicationService.Current.State["photoClip"] = App.CroppedImage;
            NavigationService.GoBack();
            
        }
        
       /* private void WriteDummyImage(BitmapImage image)
        {
            Image imageC = new Image();
            imageC.Stretch = Stretch.None;
            imageC.Source = image;
            imageC.Height = rect.Height;
            imageC.Width = rect.Width;

            WriteBitmap(imageC);
        }*/



        
    }
}